package org.lqk.file.transfer.server.processor;

import org.apache.commons.io.FilenameUtils;
import org.lqk.file.transfer.file.FileStorage;
import org.lqk.file.transfer.protocol.CmdCode;
import org.lqk.file.transfer.protocol.FileTaskRequest;
import org.lqk.file.transfer.protocol.RemotingCommand;
import org.lqk.file.transfer.protocol.RpcType;
import org.lqk.file.transfer.server.framework.AbstractFileRequestProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by Administrator on 2015/8/30.
 */
public class FileTaskRequestProcessor extends AbstractFileRequestProcessor {

	
	private static Logger log = LoggerFactory.getLogger(FileTaskRequestProcessor.class);

	public FileTaskRequestProcessor(ConcurrentHashMap<String, FileStorage> fileTable,String baseDir,int cmdCode) {
		super(fileTable,baseDir,cmdCode);
	}

	
	public RemotingCommand process(RemotingCommand request) throws IOException {
		RemotingCommand response = new RemotingCommand(CmdCode.File_Task.getCode(), RpcType.File_Response.getCode(), false,request.getOpaque());
		if (fileTable.size() >= 16) {
			response.setFlag(false);
			return response;
		}
		FileTaskRequest body = (FileTaskRequest) request.getBody();
		String fileName = body.getFileName();
		String filePath = FilenameUtils.normalize(baseDir + File.separator + fileName);
		RandomAccessFile file = new RandomAccessFile(filePath, "rw");
		FileStorage fileStorage = new FileStorage(file.getChannel(), body.getFileSize(), body.getMd5(), body.getBlockSize());
		fileTable.put(fileName, fileStorage);
		response.setFlag(true);
		return response;
	}
}
